package com.genauth.sys.controller;

import com.genauth.sys.entity.MenuBean;
import com.genauth.sys.entity.PageResponse;
import com.genauth.sys.entity.test.PageQueryBean;
import com.genauth.sys.entity.test.UserInfoBean;
import com.genauth.sys.entity.test.UserInfoQueryBean;
import com.genauth.sys.service.MenuService;
import com.genauth.sys.util.IdGen;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/genauth/menuManage")
public class MenuManageAction {

    private Logger logger = LoggerFactory.getLogger(MenuManageAction.class);

    @Resource
    private MenuService menuService;

    @ResponseBody
    @RequestMapping(value = "/getMenu.do", produces = "application/json;charset=UTF-8", method = {RequestMethod.POST})
    public PageResponse getMenu(HttpServletRequest request, PageQueryBean pb, MenuBean menuBean) throws Exception {
        PageResponse res = new PageResponse();
        List<MenuBean> menuBeans = menuService.queryMenu(menuBean);
        res.setRspData(menuBeans);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/upsertMenu.do", produces = "application/json;charset=UTF-8", method = {RequestMethod.POST})
    public PageResponse upsertMenu(HttpServletRequest request, MenuBean menuBean) throws Exception {
        PageResponse res = new PageResponse();
        int optRes = -1;
        if(!StringUtils.isAnyEmpty(menuBean.getMenuCode(),menuBean.getMenuId())){
          if(menuService.countByControllerAndCode(menuBean)==0){
              if(StringUtils.isBlank(menuBean.getMenuId())){
                  menuBean.setMenuId(IdGen.uuid());
                  optRes = menuService.insertMenu(menuBean);
              }else{
                  optRes = menuService.updateMenu(menuBean);
              }
          }else{
              optRes = -2;//菜单Code或者ControllerCode重复
          }
        }

        res.setRspData(optRes);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteMenu.do", produces = "application/json;charset=UTF-8", method = {RequestMethod.POST})
    public PageResponse deleteMenu(HttpServletRequest request, MenuBean menuBean) throws Exception {
        PageResponse res = new PageResponse();
        int optRes = 0 ;
        if(StringUtils.isNotBlank(menuBean.getMenuId())){
            optRes = menuService.deleteMenu(menuBean);
        }
        res.setRspData(optRes);
        return res;
    }
}
